package com.tx.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tx.service.UserService;
import com.tx.service.impl.UserServiceImpl;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/user/edit")
public class UserEditServlet extends HttpServlet {
    private final UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            String idStr = request.getParameter("id");
            String username = request.getParameter("username");
            String account = request.getParameter("account");
            String password = request.getParameter("password");
            String permissionStr = request.getParameter("permission");
            
            if (idStr == null || idStr.trim().isEmpty()) {
                throw new IllegalArgumentException("用户ID不能为空");
            }
            if (username == null || username.trim().isEmpty()) {
                throw new IllegalArgumentException("用户名不能为空");
            }
            if (account == null || account.trim().isEmpty()) {
                throw new IllegalArgumentException("账号不能为空");
            }
            if (permissionStr == null || permissionStr.trim().isEmpty()) {
                throw new IllegalArgumentException("权限不能为空");
            }
            
            int id = Integer.parseInt(idStr);
            int permission = Integer.parseInt(permissionStr);
            if (permission != 0 && permission != 1) {
                throw new IllegalArgumentException("权限值无效");
            }
            
            boolean success = userService.updateUser(id, username, account, password, permission);
            if (success) {
                out.println("修改成功");
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                out.println("修改失败");
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.println("修改失败：ID或权限值必须是数字");
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            out.println("修改失败：" + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.println("修改失败：" + e.getMessage());
        }
    }
} 